package com.learn.file;

import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class WordCount {
    public static void main(String[] args) {
        FileReader fr = null;
        BufferedWriter bw = null;

        try {
            // key：出现的字符；value：每个字符出现次数
            Map<Character, Integer> map= new HashMap<>();
            //创建字符流
            fr = new FileReader("io\\hello.txt");
            int ch;
            while ((ch = fr.read()) != -1){
                char character = (char)ch;
                //判断character是否首次出现
                if(map.get(character) == null){
                    map.put(character, 1);
                }else {
                    map.put(character, map.get(character) + 1);
                }
            }
            //把map中信息存入文件
            bw = new BufferedWriter(new FileWriter("wordcount.txt"));
            Set<Map.Entry<Character, Integer>> result = map.entrySet();
            for (Map.Entry<Character, Integer> entry : result) {
                switch (entry.getKey()){
                    case ' ':
                        bw.write("空格 = " + entry.getValue());
                        break;
                    case '\t':
                        bw.write("tab = " + entry.getValue());
                        break;
                    case '\r':
                        bw.write("回车 = " + entry.getValue());
                        break;
                    case '\n':
                        bw.write("换行 = " + entry.getValue());
                        break;
                    default:
                        bw.write(entry.getKey() + "=" + entry.getValue());
                }
                bw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fr != null) {
                    fr.close();
                }
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
